package cn.hd01.weixin;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hd01.repository.entity.BookRecord;
import cn.hd01.repository.entity.Customer;
import cn.hd01.service.BookRecordService;
import cn.hd01.service.CustomerService;
import cn.hd01.service.ProductService;
import cn.hd01.web.auth.Auth;
import cn.hd01.web.auth.AuthType;
import cn.hd01.web.util.WebHelper;
import cn.hd01.weixin.model.Result;

@Controller
@RequestMapping("/weixin/book")
@Auth(AuthType.WECHAT)
public class WXBookController {
	@Autowired
	private CustomerService cusomterService;
	
	@Autowired
	private BookRecordService bookService;
	
	@Autowired
	private ProductService productService;
	
	@RequestMapping(path = "", method = RequestMethod.GET)
	public String index() {
		return "weixin/agent/mybooks";
	}
	
	@ResponseBody
	@RequestMapping(path = "/list", method = RequestMethod.GET)
	public Page<BookRecord> list(@PageableDefault Pageable pageable) {
		Customer customer = cusomterService.findByOauthId(WebHelper.currentWXOauth().getId());
		BookRecord rb = new BookRecord();
		rb.setCustomerId(customer.getId());
		return bookService.findAll(rb, pageable);
	}
	
	@RequestMapping(path = "/add", method = RequestMethod.GET)
	public String add(Model m) {
		m.addAttribute("products", productService.findAll());
		return "weixin/agent/addbook";
	}
	
	@ResponseBody
	@RequestMapping(path = "/add", method = RequestMethod.POST)
	public Result add(BookRecord br) {
		Customer customer = cusomterService.findByOauthId(WebHelper.currentWXOauth().getId());
		br.setCustomerId(customer.getId());
		br.setCustomerName(customer.getName());
		br.setDistributorId(customer.getRecommendDistributorId());
		
		bookService.save(br);
		return new Result();
	}
}
